package cn.com.blueInfo.business.tpc;

import lombok.extern.log4j.Log4j2;
import org.springframework.boot.CommandLineRunner;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

@Log4j2
public class TcpServer implements CommandLineRunner {

    // 定义为局部变量，这里使用8082作为示例
    private final int port = 9080;

    private ServerSocket serverSocket;
    private volatile boolean isRunning = false;

    @Override
    public void run(String... args) throws Exception {
        startServer();
    }

    public void startServer() {
        isRunning = true;
        new Thread(() -> {
            try {
                serverSocket = new ServerSocket(port);
                log.info("TCP服务已启动，监听端口: {}", port);

                while (isRunning) {
                    // 等待log连接
                    Socket clientSocket = serverSocket.accept();
                    log.info("新log连接: {}:{}",
                            clientSocket.getInetAddress().getHostAddress(),
                            clientSocket.getPort());

                    // 启动新线程处理log
                    new Thread(() -> handleClient(clientSocket)).start();
                }
            } catch (IOException e) {
                if (isRunning) {
                    log.error("TCP服务异常", e);
                } else {
                    log.info("TCP服务已停止");
                }
            }
        }).start();
    }

    private void handleClient(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                String message = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
                log.info("收到来自 {}:{} 的数据: {}",
                        clientSocket.getInetAddress().getHostAddress(),
                        clientSocket.getPort(),
                        message);

                // 这里可以添加数据处理逻辑
                //processReceivedData(message);
            }

            log.info("log {}:{} 断开连接",
                    clientSocket.getInetAddress().getHostAddress(),
                    clientSocket.getPort());
        } catch (IOException e) {
            log.error("处理log数据出错", e);
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                log.error("关闭log连接出错", e);
            }
        }
    }

    private void processReceivedData(String data) {
        // 处理接收到的数据的业务逻辑
        log.info("处理数据: {}", data);
    }

    public void stopServer() {
        isRunning = false;
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
            log.info("TCP服务已停止");
        } catch (IOException e) {
            log.error("停止TCP服务出错", e);
        }
    }
}
